package com.liuugoqing.creator.prototype.deepclone;

import org.junit.Test;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

/**
 * @Author : liugq
 * @Date : 2022/7/1 21:59
 * @See : 参考类
 * @Since： JDK1.8
 * @Version : 1.0
 */
public class CitationTest {
    /**
     * 正常使用clone方法克隆（属于浅克隆），citation中的属性stu属于引用地址，而不是创建一个新的对象
     * @throws Exception
     */
    @Test
    public void testQ() throws Exception{
        Citation citation = new Citation();
        Student student = new Student();
        student.setName("张三");
        citation.setStu(student);

        //克隆
        Citation clone = citation.clone();
        Student stu = clone.getStu();
        stu.setName("李四");
        clone.setStu(stu);

        citation.show();
        clone.show();
        //克隆出来的student对象，指向的是一个地址
        System.out.println(student == stu);
        System.out.println(citation == clone);
    }

    /**
     * 深克隆，使用对象流
     * @throws Exception
     */
    @Test
    public void testS() throws Exception{
        //待克隆的对象
        Citation citation = new Citation();
        Student student = new Student();
        student.setName("张三");
        citation.setStu(student);
        citation.show();

        //使用流克隆
        ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("C:\\Users\\刘国庆\\Desktop\\a.txt"));
        oos.writeObject(citation);
        oos.flush();
        oos.close();
        //从文件中获取对象
        ObjectInputStream ois = new ObjectInputStream(new FileInputStream("C:\\Users\\刘国庆\\Desktop\\a.txt"));
        Citation clone = (Citation)ois.readObject();
        ois.close();
        //获取克隆出来的属性
        Student stu = clone.getStu();
        stu.setName("李四");
        clone.show();

        System.out.println(student == stu);
    }
}
